package main.leetcode.offer.secondround.from03to50;

/** 12.矩阵中的路径 */
public class ex12 {
    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (dfs(board, i, j, word, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, int i, int j, String word, int index) {
        if (i < 0
                || i >= board.length
                || j < 0
                || j >= board[0].length
                || word.charAt(index) != board[i][j]) {
            return false;
        }
        if (index == word.length() - 1) {
            return true;
        }
        char tmp = board[i][j];
        board[i][j] = '/';
        boolean res =
                dfs(board, i - 1, j, word, index + 1)
                        || dfs(board, i + 1, j, word, index + 1)
                        || dfs(board, i, j - 1, word, index + 1)
                        || dfs(board, i, j + 1, word, index + 1);
        board[i][j] = tmp;
        return res;
    }
}
